package com.sali.jsondecorator;

import com.alibaba.fastjson.JSONObject;
import com.sali.common.KafkaUtils;
import com.sali.pojo.KafkaEntity;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

public class JsonProducer extends KafkaUtils {

    public static void sendData(KafkaEntity kafkaEntity, JSONObject dataJson) {
        checkParams(kafkaEntity);

        Properties kafkaProperties = getKafkaProperties(kafkaEntity.getBrokerIp());
        kafkaProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        kafkaProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());

        // 创建kafka生产者
        Producer<String, String> producer = new KafkaProducer<>(kafkaProperties);

        ProducerRecord<String, String> record = new ProducerRecord<>(kafkaEntity.getKafkaTopic(), dataJson.toString());
        producer.send(record, (metadata, exception) -> {
            if (exception == null) {
                System.out.println("消息发送成功，Topic: " + metadata.topic() +
                        ", Partition: " + metadata.partition() +
                        ", Offset: " + metadata.offset());
            } else {
                System.err.println("消息发送失败: " + exception.getMessage());
            }
        });
        producer.close();
    }

    public static void main(String[] args) {
        final String brokerIp = "192.168.80.103:6667";
        final String kafkaTopic = "zh_json_topic001";
        KafkaEntity kafkaEntity = KafkaEntity.builder().kafkaTopic(kafkaTopic).brokerIp(brokerIp).build();

        try {
            for (int i = 0; i < 3; i++) {
                JSONObject dataJson = generateDataJson(i);
                sendData(kafkaEntity, dataJson);

                System.out.println("发送成功条数: " + (i + 1));
                Thread.sleep(2 * 1000);
            }
        } catch (Exception e) {
            System.out.println("数据发送异常" + e.getMessage());
        }
    }

    private static JSONObject generateDataJson(int i) {
        JSONObject dataJson = new JSONObject();

        dataJson.put("data_source", "datasource_" + i);
        dataJson.put("account_id", "accountId_" + i);
        dataJson.put("mobile_phone", 1000 + i);
        dataJson.put("brand", "brand_" + i);
        dataJson.put("model", "model_" + i);
        dataJson.put("price", 10.1f + i);
        dataJson.put("insert_day", 20240201);
        dataJson.put("insert_hour", 10);
        dataJson.put("insert_min", 56);

        return dataJson;
    }

}
